<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="refreshLoading"
      success-text="刷新成功"
      @refresh="getNextPageArticle"
    >
      <van-list
        v-model="loading"
        @load="getNextPageArticle"
        :immediate-check="false"
        :finished="finished"
        finished-text="别翻了~ 抄家了"
        :error.sync="error"
        error-text="请求失败"
      >
        <article-item
          v-for="item in articles"
          :key="item.art_id"
          :article-info="item"
        >
        </article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticlesAPI } from '@/api'
// 引入组件
import ArticleItem from './ArticleItem.vue'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  data () {
    // loading：标识是否处于加载中
    // 如果loading绑定false @load事件就会被调用
    // 如果loading绑定true @load事件就不会被调用
    // 每一次执行laod事件 vant自动的把loading改为true
    return {
      articles: [],
      preTimestamp: '',
      loading: false,
      finished: false,

      error: false,
      refreshLoading: false
    }
  },
  created () {
    this.getFristPageArtic()
  },
  methods: {
    // 获取第一页的文章数据
    async getFristPageArtic () {
      try {
        // 干向new.js
        // 获取时间戳： Data.now() new Data().valueOf()
        const { data } = await getArticlesAPI(this.channelId, +new Date())

        this.articles = data.data.results

        // 保存第一页的下一页的时间戳
        this.preTimestamp = data.data.pre_timestamp
      } catch (error) {
        if (error.response?.status === 400) {
          // vuex
          this.$toast.fail(error.response.data.message)
        } else {
          throw error
        }
      }
    },
    async getNextPageArticle () {
      // 发送请求
      try {
        const { data } = await getArticlesAPI(this.channelId, this.preTimestamp)

        // 添加数据
        const results = data.data.results
        // 添加到数组中
        if (this.loading) {
          this.articles.push(...results)
        } else {
          this.articles = [...results, ...this.articles]
        }

        // 更新时间戳
        this.preTimestamp = data.data.pre_timestamp

        if (data.data.pre_timestamp === null) {
          this.finished = true
        }
      } catch (error) {
        this.error = true
      } finally {
        // 手动将loading改为false
        this.loading = false
        this.refreshLoading = false
      }
    }
  },
  props: {
    channelId: [Number, String]
  }
}
</script>

<style lang="less" scoped>
.article-list {
  height: calc(100vh - 100px - 92px - 89px);
  overflow: auto;
  // less &代表 父元素的选择器
  // 1 定高   2 overflow：auto/scroll/overlay   三个属性至少选一个
  &::-webkit-scrollbar {
    width: 6px;
    background-color: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #3296fa;
    border-radius: 10px;
  }
}
</style>
